package cn.wolfcode.springcloud.controller;

import cn.wolfcode.springcloud.Order;
import cn.wolfcode.springcloud.service.IOrderService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;
@Slf4j//日志标签
@RestController
@RequestMapping("orders")
public class OrderController {

    @Autowired
    private IOrderService orderService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //降级配置
    //一旦这个save方法异常或者超时就会走fallbackMethod指定的saveFallback方法
    @HystrixCommand(fallbackMethod = "saveFallback")
    @GetMapping("/save/{userId}/{productId}")
    public Order save(@PathVariable Long userId, @PathVariable Long productId, HttpServletRequest request){
        //记录调用日志
        //log.info("OrderController-save.....");


        return orderService.save(userId, productId);

    }


    //方法签名跟接口一样但是方法名不一样
    public Order saveFallback(@PathVariable Long userId, @PathVariable Long productId, HttpServletRequest request){
        /*String cookie=request.getHeader("Cookie");
        String token=request.getHeader("token");
        System.out.println(cookie + "------" + token);*/


        System.out.println("走降级方法....");
        //在大的公司这个服务器坏了必须立即解决，否则容易造成雪崩

        //发短信或者邮寄通知
        //启动一个线程,让线程执行发短信，假如发短信失败，不会影响降级操作
        new Thread(new Runnable(){
            @Override
            public void run() {
                String redisKey = "order-save";
                String value = stringRedisTemplate.opsForValue().get(redisKey);
                if(StringUtils.isEmpty(value)){
                    System.out.println("order下订单服务失败，请查找原因.");
                    stringRedisTemplate.opsForValue().set(redisKey,"save-order-fail",20, TimeUnit.SECONDS);
                }else{
                    System.out.println("已经发送过短信");
                }
            }
        }).start();
        return new Order();
    }
}